package com.jiexinyun.utils.lock;

import com.jiexinyun.constants.RedisLockKeys;
import com.jiexinyun.holder.RedisLockContextHolder;
import com.jiexinyun.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisLockUtils {

    private static RedissonClient redissonClient;

    private static final String PREFIX = "redislock" ;

    //初始化加载
    static {
        RedisLockUtils.redissonClient = SpringUtils.getBean(RedissonClient.class);
        log.info("RedisLockUtil redissonClient init");
    }

    //工具雷中的方法，具体调用自定义实体雷中的，自定义方法

    /**
     * 优先使用
     * @param key
     * @return
     */
    public static boolean tryLock(String key) {

        try {
            RLock rLock = RedisLockUtils.redissonClient.getLock(PREFIX + ":" +key);
            int retryCount = 3;
            while (retryCount-- > 0) {
                if(rLock != null) {
                    boolean f = rLock.tryLock(100, 30, TimeUnit.SECONDS);
                    RedisLockContextHolder.buildContext(rLock);
                    return f;
                } else {
                    log.info("获取锁失败！");
                    return false;
                }

            }

        } catch (InterruptedException e) {
            log.error("lock-ERROR", e);
        }
        return false;
    }

    /**
     * 默认时间
     * @param key
     * @param var1
     * @param var3
     * @return
     */
    public static boolean tryLock(RedisLockKeys key, long var1, long var3) {

        try {
            RLock rLock = RedisLockUtils.redissonClient.getLock(PREFIX + ":" +key.name());
            int retryCount = 3;
            while (retryCount-- > 0) {
                if(rLock != null) {
                    boolean f = rLock.tryLock(var1, var3, TimeUnit.SECONDS);
                    if(f){
                        RedisLockContextHolder.buildContext(rLock);
                    }
                    return f;
                } else {
                    log.info("获取锁失败！");
                    return false;
                }

            }

        } catch (InterruptedException e) {
            log.error("lock-ERROR", e);
        }
        return false;
    }

    public static void unlock() {
        RedisLockContextHolder.clearContext();
    }

}
